using Serilog;
using FytSoa.Quartz.Extensions;
using Digitalmes.ApiService.Filters;
using Digitalmes.ApiService.Hubs;
using Digitalmes.ApiService.Middleware;
using Digitalmes.ApiService.Swagger;
using Digitalmes.Application;
using Digitalmes.Common.Extensions;
using Digitalmes.Common.Utils;
using Digitalmes.CrossCutting;
using Digitalmes.Sugar;
using Digitalmes.Scada;

var builder = WebApplication.CreateBuilder(args);

// 注册 CORS
builder.Host.ConfigureServices((hostBuilder, services) =>
{
    var origins = hostBuilder.Configuration["Cors"]?.Split(';', StringSplitOptions.RemoveEmptyEntries) ?? [];
    services.AddCors(options =>
    {
        options.AddPolicy(name: "MyCors",
            policy =>
            {
                policy.WithOrigins(origins)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .WithExposedHeaders("X-Refresh-Token");
            });
    });
});

// 注册 SignalR
builder.Services.AddSignalR();

// 注册全局筛选器
builder.Services.AddControllers(options =>
{
    options.Filters.Add<AopActionFilter>();
    options.Filters.Add<GlobalExceptionFilter>(); 
    options.Filters.Add<UnitOfWorkFilter>();
    options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
}).AddJsonOptions(options =>
{
    options.JsonSerializerOptions.AllowTrailingCommas = false;
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerConfiguration();

// 注册 HttpContext 访问器
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

// 注册应用服务
builder.Host.RegisterAppServices();

// 注册 Mapper 映射服务
builder.Services.AddMapperProfile();

// 注册本地Scada服务
builder.Host.AddScada(typeof(Program).Assembly);

// 可设置为 Window Service。
builder.Host.UseWindowsService();

// 注册Serilog日志
builder.Host.UseSerilog((hostingContext, loggerConfiguration) =>
    loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)); // 使用 Serilog，并从配置文件中读取配置。

// Build
var app = builder.Build();

app.AppSetup(); // 应用配置 

app.UseSwaggerSetup();

app.UseStaticFiles();

// 使用自定义的静态文件路径
//app.UseFileServer(new FileServerOptions
//{
//    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "upload")),
//    RequestPath = "/upload",
//});

app.UseRouting();

app.UseCors("MyCors");

// 允许反复读取
//app.Use(async (context, next) =>
//{
//    context.Request.EnableBuffering();
//    await next.Invoke();
//});

app.UseAuthentication();
app.UseAuthorization();

app.UseMiddleware<ExceptionMiddleware>();
app.UseMiddleware<JwtMiddleware>();

app.UseQuartz();

app.MapControllers()
   .RequireAuthorization();

// 注册 Hub
app.MapHub<OnlineHub>("/onlinehub");
app.MapHub<ChannelHub>("/channelhub");

app.Run();
